package net.airtheva.uniqueTask2;

import java.util.ArrayList;

import net.airtheva.uniqueTask2.view.OpenDialogBox;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;

public class SetupActivity extends Activity {

	static final int REQUEST_CODE_SELECT_BACKGROUND = 0;
	static final int REQUEST_CODE_SELECT_ICON = 1;
	static final int REQUEST_CODE_SELECT_JSON = 2;
	
	static final String[] COUNTRYIES = new String[] {
		"中国",
		"美国"
	};
	
	String mSession = null;
	
	ArrayList<Uri> mBackgroundUris = null;
	Uri mIconUri = null;
	int mSex = API.USER_SEX_UNKNOWN;
	
	RelativeLayout mBackgroundContainer = null;
	OpenDialogBox mSelectBackground = null;
	ImageView mIcon = null;
	OpenDialogBox mSelectIcon = null;
	EditText mNickname = null;
	EditText mDescription = null;
	Spinner mCountry = null;
	RadioGroup mSexRadio = null;
	RadioButton mMale = null;
	RadioButton mFemale = null;
	EditText mAge = null;
	EditText mFollowers = null;
	EditText mEmail = null;
	Button mSave = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setup);
		
		mBackgroundUris = new ArrayList<Uri>();
		
		mBackgroundContainer = (RelativeLayout) findViewById(R.id.activity_setup_backgroundContainer);
		
		mSelectBackground = (OpenDialogBox) findViewById(R.id.activity_setup_selectBackground);
		
		mSelectBackground.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				SetupActivity.this.startActivityForResult(intent, REQUEST_CODE_SELECT_BACKGROUND);
				
			}
			
		});
		
		mIcon = (ImageView) findViewById(R.id.activity_setup_icon);
		
		mSelectIcon = (OpenDialogBox) findViewById(R.id.activity_setup_selectIcon);
				
		mSelectIcon.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				SetupActivity.this.startActivityForResult(intent, REQUEST_CODE_SELECT_ICON);
				
			}
			
		});
		
		mNickname = (EditText) findViewById(R.id.activity_setup_nickname);
		
		mDescription = (EditText) findViewById(R.id.activity_setup_description);
		
		mCountry = (Spinner) findViewById(R.id.activity_setup_country);
		
		mCountry.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, COUNTRYIES));
		
		mSexRadio = (RadioGroup) findViewById(R.id.activity_setup_sex);
		
		mSexRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				if(checkedId == mMale.getId()) {
					mSex = API.USER_SEX_MALE;
				}
				else if(checkedId == mFemale.getId()) {
					mSex = API.USER_SEX_FEMALE;
				}
			}
		});
		
		mMale = (RadioButton) findViewById(R.id.activity_setup_male);
		
		mFemale = (RadioButton) findViewById(R.id.activity_setup_female);
		
		mAge = (EditText) findViewById(R.id.activity_setup_age);
		
		mFollowers = (EditText) findViewById(R.id.activity_setup_followers);
		
		mEmail = (EditText) findViewById(R.id.activity_setup_email);
		
		mSave = (Button) findViewById(R.id.activity_setup_save);
		
		mSave.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Response res = API.GetInstance(SetupActivity.this).UpdateProfile(mSession, SaveAsJSON());
				switch(res.GetStatusCode()) {
				case Response.STATUS_CODE_SUCCESS:
					
					if(getIntent().getBooleanExtra("return", false)) {
						finish();
					}
					else {
						Intent intent = new Intent(SetupActivity.this, UserActivity.class);
						intent.putExtra("session", mSession);
						startActivity(intent);
					}
					
					break;
				default:
					Toast.makeText(SetupActivity.this, res.GetExtra(), Toast.LENGTH_SHORT).show();
					break;
				}
			}
			
		});

		Intent intent = getIntent();
		mSession = intent.getStringExtra("session");
		Response res = API.GetInstance(this).FetchProfile(mSession, API.USER_ID_UNKNOWN);
		switch(res.GetStatusCode()) {
		case Response.STATUS_CODE_SUCCESS:
			LoadViaJSON(res.GetExtra());
			break;
		default:
			Toast.makeText(SetupActivity.this, res.GetExtra(), Toast.LENGTH_SHORT).show();
			break;
		}
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(resultCode == Activity.RESULT_OK) {
			switch(requestCode) {
			case REQUEST_CODE_SELECT_BACKGROUND:
				Uri uri = data.getData();
				AddBackground(uri);
				break;
			case REQUEST_CODE_SELECT_ICON:
				SetIcon(data.getData());
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	void AddBackground(Uri uri) {
		mBackgroundUris.add(uri);
		// FIXME: Did not work as expected.
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
		int margin = (mBackgroundUris.size() - 1) * 4;
		lp.setMargins(margin, margin, margin, margin);
		ImageView imageView = new ImageView(this);
		imageView.setImageURI(Uri.parse(Utils.CacheBackgroundImage(this, uri.toString())));
		imageView.setLayoutParams(lp);
		mBackgroundContainer.addView(imageView);
	}
	
	void SetIcon(Uri uri) {
		mIconUri = uri;
		mIcon.setImageURI(Uri.parse(Utils.CacheIconImage(this, uri.toString())));
	}
	
	void SetNickname(String nickname) {
		mNickname.setText(nickname);
	}

	void SetDescription(String description) {
		mDescription.setText(description);
	}

	void SetCountry(int country) {
		if(country >= 0) {
			mCountry.setSelection(country);
		}
	}

	void SetSex(int sex) {
		switch(sex) {
		case API.USER_SEX_MALE:
			mMale.setSelected(true);
			mFemale.setSelected(false);
			break;
		case API.USER_SEX_FEMALE:
			mMale.setSelected(false);
			mFemale.setSelected(true);
			break;
		default:
			mSex = API.USER_SEX_UNKNOWN;
			mMale.setSelected(false);
			mFemale.setSelected(false);
			break;
		}
	}

	void SetAge(int age) {
		mAge.setText(age + "");
	}

	void SetEmail(String email) {
		mEmail.setText(email);
	}

	void SetFollowers(JSONArray followers) {
		try {
			mFollowers.setText(followers.join(","));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	String SaveAsJSON() {
		
		try {
			JSONObject json = new JSONObject();
			
			JSONArray backgroundUris = new JSONArray();
			for(int i = 0; i < mBackgroundUris.size(); i++) {
				
				Uri backgroundUri = (Uri) mBackgroundUris.get(i);
				backgroundUris.put(backgroundUri.toString());
				
			}
			json.put("backgroundUris", backgroundUris);
			
			json.put("iconUri", mIconUri == null ? "" : mIconUri.toString());
			json.put("nickname", mNickname.getText().toString());
			json.put("description", mDescription.getText().toString());
			json.put("country", mCountry.getSelectedItemPosition());
			json.put("sex", mSex);
			json.put("age", Integer.parseInt(mAge.getText().toString()));
			json.put("email", mEmail.getText().toString());
			
			String[] followers = mFollowers.getText().toString().split(",");
			JSONArray followers0 = new JSONArray();
			try {
				
				for(int i = 0; i < followers.length; i++) {
					
					followers0.put(Integer.parseInt(followers[i]));
				}
				
			} catch(Exception e) {
				e.printStackTrace();
			}
			json.put("followers", followers0);
			
			return json.toString(4);
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
		
	}
	
	void LoadViaJSON(String jsonString) {
	
		try {
			JSONObject json = new JSONObject(jsonString);
			
			mBackgroundContainer.removeAllViews();
			mBackgroundUris.clear();
			JSONArray backgroundUris = json.getJSONArray("backgroundUris");
			for(int i = 0; i < backgroundUris.length(); i++) {
				
				AddBackground(Uri.parse(backgroundUris.getString(i)));
				
			}
			
			SetIcon(Uri.parse(json.getString("iconUri")));
			
			SetNickname(json.getString("nickname"));
			
			SetDescription(json.getString("description"));
			
			SetCountry(json.getInt("country"));
			
			SetSex(json.getInt("sex"));
			
			SetAge(json.getInt("age"));
			
			SetEmail(json.getString("email"));
			
			SetFollowers(json.getJSONArray("followers"));
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
}
